﻿using ConfExpert.Forms.Base;
using Extensions;
using System;
using System.Data;
using System.Windows.Forms;

namespace ConfExpert.Forms.Araclar
{
    public partial class Barkod : XForm
    {
        int BarkodSayId;
        public Barkod()
        {
            InitializeComponent();
        }

        int Digits, ParityBits;
        DataTable dt = new DataTable();
        private void Barkod_Load(object sender, EventArgs e)
        {

            using (BarkodSay s = new BarkodSay())
            {
                if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Digits = s.Digits;
                    ParityBits = s.ParityBits;
                    BarkodSayId = s.BarkodSayId;

                    DataTable dt = ExecuteDataTable("GetBarkodSayLines", BarkodSayId);
                    dt.PrimaryKey = new DataColumn[] { dt.Columns["BarkodSayLinesId"] };

                    gridView1.Init(dt);
                    gridView1.MakeColumnInvisible("BarkodSayId", "BarkodSayLinesId");
                    gridView1.AddSummary();
                    gridView1.BestFitColumns();

                    this.KeyPreview = true;
                    this.KeyPress += Barkod_KeyPress;
                    btnRapor.ItemClick += btnRapor_ItemClick;
                }
            }

        }

        void btnRapor_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (BarkodRapor s = new BarkodRapor(BarkodSayId))
                s.ShowDialog();
        }


        string barCode = string.Empty;

        void Barkod_KeyPress(object sender, KeyPressEventArgs e)
        {
            bool isDigit = Char.IsDigit(e.KeyChar);
            if (isDigit)
            {
                barCode += e.KeyChar.ToString();
                if (barCode.Length == Digits)
                {
                    string realCode = barCode.Substring(0, Digits - ParityBits);
                    if (realCode != string.Empty)
                    {
                        try
                        {
                            gridView1.VeriyiGuncelle(false, "UpdBarkodSayLines", realCode, BarkodSayId, DBNull.Value);
                            txtInfo.Caption = realCode.ToString();
                            gridView1.BestFitColumns();
                            gridView1.MoveLast();
                        }
                        catch (Exception)
                        {
                            barCode = string.Empty;
                        }
                    }

                    barCode = string.Empty;
                }
            }
            else
            {
                barCode = string.Empty;
            }
        }


    }
}
